package com.zhongge.gui;

import com.zhongge.book.Book;
import com.zhongge.book.BookList;
import com.zhongge.operations.BorrowBook;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 借阅图书对话框
 */
public class BorrowBookDialog extends JDialog {
    private BookList bookList;
    private JTextField nameField;
    private boolean borrowCompleted = false;
    
    public BorrowBookDialog(Frame parent, BookList bookList) {
        super(parent, "借阅图书", true);
        this.bookList = bookList;
        initUI();
        setSize(400, 200);
        setLocationRelativeTo(parent);
    }
    
    /**
     * 初始化界面
     */
    private void initUI() {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        
        // 输入面板
        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JLabel nameLabel = new JLabel("书名: ");
        nameField = new JTextField(20);
        JButton searchButton = new JButton("查找");
        searchButton.addActionListener(new SearchListener());
        
        inputPanel.add(nameLabel);
        inputPanel.add(nameField);
        inputPanel.add(searchButton);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        JButton borrowButton = new JButton("借阅");
        JButton cancelButton = new JButton("取消");
        
        borrowButton.addActionListener(new BorrowListener());
        cancelButton.addActionListener(e -> dispose());
        
        buttonPanel.add(borrowButton);
        buttonPanel.add(cancelButton);
        
        // 添加到主面板
        mainPanel.add(inputPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        setContentPane(mainPanel);
    }
    
    /**
     * 查找按钮监听器
     */
    private class SearchListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String bookName = nameField.getText().trim();
            if (bookName.isEmpty()) {
                JOptionPane.showMessageDialog(BorrowBookDialog.this, 
                        "请输入书名", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            // 查找图书并检查状态
            StringBuilder status = new StringBuilder();
            boolean found = false;
            
            for (int i = 0; i < bookList.getUsedSize(); i++) {
                Book book = bookList.getBook(i);
                if (bookName.equals(book.getName())) {
                    found = true;
                    status.append("找到图书《").append(bookName).append("》\n");
                    status.append("作者: ").append(book.getAuthor()).append("\n");
                    status.append("状态: ").append(book.isBorrow() ? "已借出" : "可借阅");
                    break;
                }
            }
            
            if (found) {
                JOptionPane.showMessageDialog(BorrowBookDialog.this, 
                        status.toString(), "图书信息", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(BorrowBookDialog.this, 
                        "未找到图书《" + bookName + "》", "提示", JOptionPane.WARNING_MESSAGE);
            }
        }
    }
    
    /**
     * 借阅按钮监听器
     */
    private class BorrowListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String bookName = nameField.getText().trim();
            if (bookName.isEmpty()) {
                JOptionPane.showMessageDialog(BorrowBookDialog.this, 
                        "请输入书名", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            // 检查图书是否存在且可借阅
            Book targetBook = null;
            for (int i = 0; i < bookList.getUsedSize(); i++) {
                Book book = bookList.getBook(i);
                if (bookName.equals(book.getName())) {
                    targetBook = book;
                    break;
                }
            }
            
            if (targetBook == null) {
                JOptionPane.showMessageDialog(BorrowBookDialog.this, 
                        "未找到图书《" + bookName + "》", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            if (targetBook.isBorrow()) {
                JOptionPane.showMessageDialog(BorrowBookDialog.this, 
                        "图书《" + bookName + "》已借出", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            // 调用原有BorrowBook实现借阅功能
            BorrowBook borrowOperation = new BorrowBook();
            
            // 创建自定义输入流模拟控制台输入
            ConsoleInputSimulator inputSimulator = new ConsoleInputSimulator();
            inputSimulator.provideInput(bookName + "\n");
            inputSimulator.startSimulation();
            
            try {
                // 执行借阅操作
                borrowOperation.work(bookList);
                
                // 检查是否借阅成功
                if (targetBook.isBorrow()) {
                    borrowCompleted = true;
                    JOptionPane.showMessageDialog(BorrowBookDialog.this, 
                            "图书《" + bookName + "》借阅成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(BorrowBookDialog.this, 
                            "借阅失败，请重试", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(BorrowBookDialog.this, 
                        "借阅失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            } finally {
                inputSimulator.stopSimulation();
            }
        }
    }
    
    /**
     * 判断借阅是否完成
     */
    public boolean isBorrowCompleted() {
        return borrowCompleted;
    }
    
    /**
     * 控制台输入模拟工具类
     */
    private class ConsoleInputSimulator {
        private java.io.ByteArrayInputStream inBuffer;
        private java.io.InputStream originalIn;
        
        public void provideInput(String input) {
            inBuffer = new java.io.ByteArrayInputStream(input.getBytes());
        }
        
        public void startSimulation() {
            originalIn = System.in;
            System.setIn(inBuffer);
        }
        
        public void stopSimulation() {
            System.setIn(originalIn);
        }
    }
}